package be.dmlights;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * Created by IntelliJ IDEA.
 * User: toonv
 * Date: 21/05/13
 * Time: 14:36
 * To change this template use File | Settings | File Templates.
 */

public class UpsFactuurverwerker {

    private final static Logger LOGGER = Logger.getLogger(UpsFactuurverwerker.class.getName());
    static private FileHandler fileTxt;
    private static Properties prop = new Properties();

    public static void main(String[] args) throws IOException {

        prop.load(new FileInputStream(".." + File.separator + "conf" + File.separator+  "upsfactuurverwerker.properties"));
        fileTxt = new FileHandler(prop.getProperty("app.logfile"));
        fileTxt.setFormatter(new SimpleFormatter());
        LOGGER.addHandler(fileTxt);
        LOGGER.log(Level.INFO, "service started");
        Boolean running = true;
        while (running) {
            new CallLoop().run();
        }

    }

    private static class CallLoop implements Runnable {
        public void run() {
            try {
                URL myURL = new URL(prop.getProperty("app.callurl"));
                LOGGER.log(Level.INFO, "connecting to URL: " + myURL.toString());
                URLConnection myURLConnection = myURL.openConnection();
                myURLConnection.connect();
                //read content of url
                // open the stream and put it into BufferedReader
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(myURLConnection.getInputStream()));
                logContent(br);
                Thread.sleep(new Long(prop.getProperty("app.call.interval","60000")));
            } catch (MalformedURLException e) {
                LOGGER.log(Level.INFO, "malformed URL!");
            } catch (IOException e) {
                LOGGER.log(Level.INFO, "openconnection() failed!");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        private void logContent(BufferedReader reader) throws IOException {
            String line;
            while ((line = reader.readLine()) != null) {
                LOGGER.log(Level.INFO, line);
            }
        }
    }

}
